﻿package com.xuanque.mahjongDice.ScrollBarui{
	import flash.display.*;
	import flash.events.*;
	import utils.transitions.*;

	public class ScrollBoxDealWith extends EventDispatcher {
		private var _stage:DisplayObjectContainer;
		
		private var content_mc:DisplayObjectContainer;
		private var mask_mc:DisplayObjectContainer;
		private var scrollbarX:ScrollBarX;
		private var scrollbarY:ScrollBarY;

		private var newWidth:Number;
		private var newHeight:Number;
		public var _width:Number;
		public var _height:Number;

		public function ScrollBoxDealWith(content_mc:DisplayObjectContainer,mask_mc:DisplayObjectContainer,scrollbarX:ScrollBarX,scrollbarY:ScrollBarY,stage):void {
			this._stage = stage;
			
			this.mask_mc = mask_mc;
			this.content_mc = content_mc;
			content_mc.mask = this.mask_mc;
			
			this.scrollbarX = scrollbarX;
			this.scrollbarY = scrollbarY;
			
			DealWithChildren();
			addListener();
		}
		private function DealWithChildren():void {
			
			scrollbarX.visible = scrollbarY.visible = false;
			this.dispatch();
			
			this._width = scrollbarY.x + scrollbarY.width;
			this._height = scrollbarX.y + scrollbarX.height;
			
			this._stage.addEventListener(ScrollBoxEvent.THUMB_VALUE, sbChange);
		}
		private function dispatch() {
			this.newHeight = scrollbarY.track.height * (1 - (content_mc.height - mask_mc.height) / content_mc.height);
			this.newWidth = scrollbarX.track.width * (1 - (content_mc.width - mask_mc.width) / content_mc.width);
			var scrollboxevent:ScrollBoxEvent = new ScrollBoxEvent();
			scrollboxevent.h = this.newHeight;
			scrollboxevent.w = this.newWidth;
			dispatchEvent(scrollboxevent);

			scrollbarX.newWidth(scrollboxevent.w);
			scrollbarY.newHeight(scrollboxevent.h);
		}
		private function addListener() {
			if (content_mc.width > mask_mc.width) {
				scrollbarX.visible = true;
				scrollbarX.addEventListener(ScrollBarXEvent.VALUE_CHANGED, scrollbarXChange);
			}
			if (content_mc.height > mask_mc.height) {
				scrollbarY.visible = true;
				scrollbarY.addEventListener(ScrollBarYEvent.VALUE_CHANGED, scrollbarYChange);
			}
		}
		private function scrollbarXChange(event:ScrollBarXEvent):void {
			Tweener.addTween(content_mc,{x:- event.scrollPercent * (content_mc.width - mask_mc.width),time:1});
		}
		private function scrollbarYChange(event:ScrollBarYEvent):void {
			Tweener.addTween(content_mc,{y:- event.scrollPercent * (content_mc.height - mask_mc.height),time:1});
		}
		private function sbChange(event:ScrollBoxEvent):void {

			Tweener.addTween(scrollbarY.thumb, { y: (scrollbarY.track.height - scrollbarY.thumb.height), time:1 } );
			Tweener.addTween(content_mc, { y: - 1 * (content_mc.height - mask_mc.height), time:1 } );

		}
		
	}
}